﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
using WalkingTec.Mvvm.Mvc;
using TyMES.ViewModel.Record.EnergyConsumptionRecordVMs;
using TyMES.Model.Record;
using TyMES.Communication.Request;
using TyMES.Communication;
using TyMES.Communication.Response;
using Azure;

namespace TyMES.Controllers
{
    [Area("Record")]
    [AuthorizeJwtWithCookie]
    [ActionDescription("能耗记录")]
    [ApiController]
    [Route("api/EnergyConsumptionRecord")]
	public partial class EnergyConsumptionRecordController : BaseApiController
    {
        [ActionDescription("Sys.Search")]
        [HttpPost("Search")]
		public IActionResult Search(EnergyConsumptionRecordSearcher searcher)
        {
            if (ModelState.IsValid)
            {
                var vm = Wtm.CreateVM<EnergyConsumptionRecordListVM>(passInit: true);
                vm.Searcher = searcher;
                return Content(vm.GetJson());
            }
            else
            {
                return BadRequest(ModelState.GetErrorJson());
            }
        }

        [ActionDescription("Sys.Get")]
        [HttpGet("{id}")]
        public EnergyConsumptionRecordVM Get(string id)
        {
            var vm = Wtm.CreateVM<EnergyConsumptionRecordVM>(id);
            return vm;
        }

        [ActionDescription("Sys.Create")]
        [HttpPost("Add")]
        public IActionResult Add(EnergyConsumptionRecordVM vm)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                vm.DoAdd();
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState.GetErrorJson());
                }
                else
                {
                    return Ok(vm.Entity);
                }
            }

        }

        [ActionDescription("Sys.Edit")]
        [HttpPut("Edit")]
        public IActionResult Edit(EnergyConsumptionRecordVM vm)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                vm.DoEdit(false);
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState.GetErrorJson());
                }
                else
                {
                    return Ok(vm.Entity);
                }
            }
        }

		[HttpPost("BatchDelete")]
        [ActionDescription("Sys.Delete")]
        public IActionResult BatchDelete(string[] ids)
        {
            var vm = Wtm.CreateVM<EnergyConsumptionRecordBatchVM>();
            if (ids != null && ids.Count() > 0)
            {
                vm.Ids = ids;
            }
            else
            {
                return Ok();
            }
            if (!ModelState.IsValid || !vm.DoBatchDelete())
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                return Ok(ids.Count());
            }
        }


        [ActionDescription("Sys.Export")]
        [HttpPost("ExportExcel")]
        public IActionResult ExportExcel(EnergyConsumptionRecordSearcher searcher)
        {
            var vm = Wtm.CreateVM<EnergyConsumptionRecordListVM>();
            vm.Searcher = searcher;
            vm.SearcherMode = ListVMSearchModeEnum.Export;
            return vm.GetExportData();
        }

        [ActionDescription("Sys.CheckExport")]
        [HttpPost("ExportExcelByIds")]
        public IActionResult ExportExcelByIds(string[] ids)
        {
            var vm = Wtm.CreateVM<EnergyConsumptionRecordListVM>();
            if (ids != null && ids.Count() > 0)
            {
                vm.Ids = new List<string>(ids);
                vm.SearcherMode = ListVMSearchModeEnum.CheckExport;
            }
            return vm.GetExportData();
        }

        [ActionDescription("Sys.DownloadTemplate")]
        [HttpGet("GetExcelTemplate")]
        public IActionResult GetExcelTemplate()
        {
            var vm = Wtm.CreateVM<EnergyConsumptionRecordImportVM>();
            var qs = new Dictionary<string, string>();
            foreach (var item in Request.Query.Keys)
            {
                qs.Add(item, Request.Query[item]);
            }
            vm.SetParms(qs);
            var data = vm.GenerateTemplate(out string fileName);
            return File(data, "application/vnd.ms-excel", fileName);
        }

        [ActionDescription("Sys.Import")]
        [HttpPost("Import")]
        public ActionResult Import(EnergyConsumptionRecordImportVM vm)
        {
            if (vm!=null && (vm.ErrorListVM.EntityList.Count > 0 || !vm.BatchSaveData()))
            {
                return BadRequest(vm.GetErrorJson());
            }
            else
            {
                return Ok(vm?.EntityList?.Count ?? 0);
            }
        }

        [ActionDescription("上传能耗记录")]
        [HttpPost("AddEnergyRecord")]

        public ResponseBase AddEnergyRecord(EnergyConsumption.Scadarequest scadarequest)
        {
            try
            {
                EnergyConsumptionRecord energyRecord = new EnergyConsumptionRecord();
                energyRecord.stationCode = scadarequest.Station;
                energyRecord.Airpressure = scadarequest.Airpressure;
                energyRecord.Flow = scadarequest.Flow;
                energyRecord.Energy = scadarequest.Energy;
                energyRecord.VoltageA = scadarequest.VoltageA;
                energyRecord.VoltageB = scadarequest.VoltageB;
                energyRecord.VoltageC = scadarequest.VoltageC;
                energyRecord.ElectricityA = scadarequest.ElectricityA;
                energyRecord.ElectricityB = scadarequest.ElectricityB;
                energyRecord.ElectricityC = scadarequest.ElectricityC; 
                energyRecord.Time = scadarequest.Time;

                energyRecord.UploadTime = DateTime.Now;
                DC.Set<EnergyConsumptionRecord>().Add(energyRecord);
                DC.SaveChanges();
                return new ResponseBase(true, "能耗记录保存产线mes成功");
            }
            catch (Exception ex)
            {
                return new ResponseBase(false, "能耗记录保存产线mes失败"+ex.Message);
            }
        }

        //获取产线近8小时能耗数据数组
        [ActionDescription("能耗显示数据获取")]
        [HttpPost("GetEnergyUIInfo")]

        public EnergyConsumptionResponse.EnergyUIInfo GetEnergyUIInfo(LineAndStation lineAndStation)
        {
            EnergyConsumptionResponse.EnergyUIInfo energy = new EnergyConsumptionResponse.EnergyUIInfo();
            energy.energyConsumption = new List<double>();
            energy.TimeRecent = new List<string>();
            double[] es = new double[8];
            var energyarray = DC.Set<EnergyConsumptionRecord>().Where(x=>x.stationCode==lineAndStation.stationCode).OrderByDescending(x=>x.UploadTime).ToList();
            if(energyarray.Count > 8) {
                try
                {
                    for(int i = 0; i < 8; i++)
                    {
                        es[i] = Convert.ToDouble(energyarray[i].Energy);
                        energy.energyConsumption.Add(Convert.ToDouble(energyarray[i].Energy));
                        energy.TimeRecent.Add(energyarray[i].Time.ToString());

                    }
                    energy.max = es.Max();
                    energy.min = es.Min();
                    
                }
                catch(Exception ex)
                {

                }
            }
            else
            {
                try
                {
                    for (int i = 0; i < energyarray.Count; i++)
                    {
                        es[i] = Convert.ToDouble(energyarray[i].Energy);
                        energy.energyConsumption.Add(Convert.ToDouble(energyarray[i].Energy));
                        energy.TimeRecent.Add(energyarray[i].Time.ToString());
                    }
                    for(int i = energyarray.Count; i < 8; i++)
                    {
                        es[i] = 0;
                        energy.energyConsumption.Add(0);
                    }
                    energy.max = es.Max();
                    energy.min = es.Min();

                }
                catch (Exception ex)
                {

                }
            }
            return energy;
        }
    }
}
